package org.example.JUC;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

public class CopyOnWriteTest {

    private static CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>();

    public static void main(String[] args) throws InterruptedException {

        new Worker("aaa").start();
        TimeUnit.MILLISECONDS.sleep(10);
        new Worker("bbb").start();
        TimeUnit.MILLISECONDS.sleep(20);
        System.out.println(copyOnWriteArrayList);
    }

    static class Worker extends Thread {

        private String element;

        public Worker(String element) {
            this.element = element;
        }

        @Override
        public void run() {
            System.out.println("写之前，读到数据：" + copyOnWriteArrayList);
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            copyOnWriteArrayList.add(element);
        }
    }
}
